package com.learning.thread.juc.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ClassName: ConditionTest
 * Description: Condition实现线程同步协作
 * Date: 2016/11/26 17:45
 *
 * @author SAM SHO
 * @version V1.0
 */
public class ConditionTest {

    public static void main(String[] args) {
        ObjectData data = new ObjectData();
        new Thread(new MainThread(data), "MainThread_").start();
        new Thread(new SubThread(data), "SubThread_").start();
    }

    static class MainThread implements Runnable {

        private ObjectData data;

        public MainThread(ObjectData data) {
            this.data = data;
        }

        @Override
        public void run() {
            for (int i = 0; i < 3; i++) {
                data.mainMethod(i);
            }
        }
    }

    static class SubThread implements Runnable {

        private ObjectData data;

        public SubThread(ObjectData data) {
            this.data = data;
        }

        @Override
        public void run() {
            for (int i = 0; i < 3; i++) {
                data.subMethod(i);
            }
        }
    }

    /**
     * 数据业务类
     */
    static class ObjectData {
        /**
         * 注意：同一个锁对象
         */
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        /**
         * sub 方法先处理
         */
        private boolean subFirst = true;

        void mainMethod(int index) {
            lock.lock();//锁掉

            try {
                while (subFirst) {
                    condition.await();//等待
                }

                for (int i = 0; i <= 2; i++) {
                    System.out.println(Thread.currentThread().getName() + i + ", 第" + index + "循环");
                }

                subFirst = true;
                condition.signal();//唤醒
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();//解锁
            }
        }

        void subMethod(int index) {
            lock.lock();//锁掉
            try {
                while (!subFirst) {
                    condition.await();//等待
                }

                for (int i = 0; i <= 5; i++) {
                    System.out.println(Thread.currentThread().getName() + i + ", 第" + index + "循环");
                }
                subFirst = false;
                condition.signal();//唤醒
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();//解锁
            }
        }
    }
}
